<?php
/**
 * Created by PhpStorm.
 * User: jurentech
 * Date: 2019-06-24
 * Time: 11:29
 */
namespace app\master\controller;

use PHPExcel;

class Mation extends Base
{

    public function index()
    {
        if(request()->isPost()){
            //import('phpexcel.PHPExcel', EXTEND_PATH);//方法二
            vendor("PHPExcel.PHPExcel"); //方法一
            $objPHPExcel = new \PHPExcel();

            //获取表单上传文件
            $file = request()->file('excel');
            $info = $file->validate(['ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'excel');

            if($info){
                $exclePath = $info->getSaveName();  //获取文件名
                $file_name = ROOT_PATH . 'public' . DS . 'excel' . DS . $exclePath;   //上传文件的地址
                $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
                $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8

                $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
                array_shift($excel_array);  //删除第一个数组(标题);
                $data = [];
                $i=0;
                foreach($excel_array as $k=>$v) {
                    $data[$k]['user_phone'] = $v[0];
                    $data[$k]['company'] = $v[1];
                    $data[$k]['status'] = $v[2];
                    $i++;
                }
                $success=db('mation')->insertAll($data); //批量插入数据

                $error=$i-$success;
                return $this->success("总{$i}条，成功{$success}条，失败{$error}条。");


            }else{
                // 上传失败获取错误信息
                return $this->error($file->getError());
            }
        }
        return $this->fetch();
    }


    public function getlist()
    {
        $page['page'] = input("page");
        $page['limit'] = input("limit");
        $result['data'] = db('mation')
            ->where(['type' => ['neq', 3]])
            ->order('mation_id DESC')
            ->page($page['page'], $page['limit'])
            ->select();

        $result['count'] = db('mation')->where(['type' => ['neq', 3]])->count();
        return $this->_table_return(0, "", $result['count'], $result['data']);
    }

    public function hdelete()
    {
        $id = input('id');
        db('mation')->where(['mation_id' => $id])->update(['type' => 3]);
        return $this->_ajax_return(200, '成功');
    }
}